import hashlib
import time
from django.core.cache import cache
from django.utils import timezone
from .models import SMSRecord
from .providers import get_sms_provider

class SMSService:
    @staticmethod
    def generate_code() -> str:
        return ''.join([str(i) for i in range(6)])  # 实际应使用随机数

    @staticmethod
    def create_session_id(request) -> str:
        """生成会话标识"""
        if request.user.is_authenticated:
            return f"user_{request.user.id}"
        ip = request.META.get('REMOTE_ADDR', '')
        ua = request.META.get('HTTP_USER_AGENT', '')[:30]
        return f"anon_{hashlib.md5(f'{ip}_{ua}'.encode()).hexdigest()}"

    @classmethod
    def send_code(cls, request, phone: str, purpose: str) -> bool:
        # 频率控制（示例：同一会话1分钟内不能重复发送）
        cache_key = f"sms_limit_{cls.create_session_id(request)}_{purpose}"
        if cache.get(cache_key):
            return False
        
        code = cls.generate_code()
        expires_at = timezone.now() + timezone.timedelta(minutes=5)
        
        # 创建记录
        SMSRecord.objects.create(
            phone=phone,
            purpose=purpose,
            code=code,
            session_id=cls.create_session_id(request),
            expires_at=expires_at
        )
        
        # 调用服务商发送
        success = get_sms_provider().send(phone, code, purpose)
        
        # 设置频率限制
        if success:
            cache.set(cache_key, True, 60)  # 1分钟冷却
        return success

    @classmethod
    def verify_code(cls, request, phone: str, code: str, purpose: str) -> bool:
        record = SMSRecord.objects.filter(
            phone=phone,
            purpose=purpose,
            code=code,
            is_used=False,
            expires_at__gte=timezone.now(),
            session_id=cls.create_session_id(request)
        ).first()
        
        if record:
            record.is_used = True
            record.save()
            return True
        return False